package cn.johnyu.util;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    public static SqlSessionFactory getSqlSessionFactory() {
        if(sqlSessionFactory==null){
            String resource = "mybatis-config.xml";
            try(InputStream inputStream = Resources.getResourceAsStream(resource)){
                sqlSessionFactory = new  MybatisSqlSessionFactoryBuilder()
                        .build(inputStream);
                // 分页插件
                MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
                interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
                sqlSessionFactory.getConfiguration().addInterceptor(interceptor);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }

    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
        System.out.println(sqlSession);
    }
}
